#!/usr/bin/python3
import re
import sys
import os
import time
strAll=""
# os.walk()遍历文件夹下的所有文件
# os.walk()获得三组数据(rootdir, dirname,filnames)
def file_path(file_dir,strPath):
    global strAll
    for root, dirs, files in os.walk(file_dir):
        # print(root, end=' ')    # 当前目录路径
        # print(dirs, end=' ')    # 当前路径下的所有子目录
        # print(files)            # 当前目录下的所有非目录子文件
        for f in files:
            replace(root,f,strPath)

def replace(root,f,strPath):
    global strAll,path
    filePath=root+"/"+f
    fOrigin=f
    fo = open(filePath, "r+")
    line = fo.read()
    pattern = re.compile(r'("[^"]*?[^\\]?")')   # 查找"""
    result1 = pattern.findall(line)
    fo.close()
    prefix='app'
    startIndex=1

    for a in range(0,len(result1)):
        zhPattern = re.compile(u'[\u4e00-\u9fa5]+')# 查找汉字
        match = zhPattern.search(result1[a])
        if match:
            if fOrigin.find(".xml")!=-1:
                f=fOrigin.replace(".xml","")
                print(fOrigin)
                print(result1[a])
                strAll=strAll+'    <string name="'+prefix+'Xml'+f+str(a+startIndex)+'\">'+result1[a].replace('"','')+'</string>\n'
                os.system("sh changexml.sh '"+result1[a]+"' "+prefix+'Xml'+f+str(a+startIndex)+" "+filePath+" "+result1[a].replace("\"","")+" "+strPath)
            elif fOrigin.find(".java")!=-1:
                f=fOrigin.replace(".java","")
                print(fOrigin)
                print(result1[a])
                strAll=strAll+'    <string name="'+prefix+'Java'+f+str(a+startIndex)+'\">'+result1[a].replace('"','')+'</string>\n'
                os.system("sed -i 's/"+result1[a].replace("/","\\/")+"/App.INSTANCE.getString(R.string."+prefix+'Java'+f+str(a+startIndex)+")/g' "+filePath)

# path=sys.argv[1]
# strPath=sys.argv[2]
path="/home/lv/python/python_tools/抽取java文件及xml文件的汉字到strings.xml中/test/"
strPath = "/home/lv/python/python_tools/抽取java文件及xml文件的汉字到strings.xml中/strings.xml"
strFile=open(strPath, "r+")
read_data = strFile.read()
strFile.seek(0)
strFile.truncate()
file_path(path,strPath)
strFile.write(read_data.replace('</resources>', strAll+'</resources>'))